
import React from "react";
import "./index.less";

import Icon from 'bee-icon';
import 'bee-icon/build/Icon.css';
import Button from 'bee-button';
import 'bee-button/build/Button.css';

import createYGCPage from '../../components/CreateYGCPage/index.jsx';
import HeaderCheckbox from './components/HeaderCheckbox/index.jsx'
import Form from './components/Form/index.jsx'
import TreeBtnGroup from './components/TreeBtnGroup/index.jsx'
import Refer from './components/refer/index.jsx'

import { btnTpl } from './tpl';
import { URL } from './engineeringLocation.config.js';

class EngineeringLocation extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            data: [],
        };

        this.buttonHandlers = {
            cancel: this.cancelClick,
            save: this.saveClick,
            editSave: this.editSaveClick,
            editCancel: this.editCancelClick,
            print: this.printClick,
            refresh: this.refreshClick,
            treeEdit: this.treeEditClick,
            treeAddBor: this.treeAddBorClick,
            treeAddChild: this.treeAddChildClick,
            treeDel: this.treeDelClick
        }
        this.saveFlag = 'add'
    }

    render() {
        let { searchTpl, pageState } = this.state;
        console.log(this.props.search)
        return (

            <div className="ygc-treeCard">
                <div className='ygc-treeCard-header-area'>
                    <div className='ygc-treeCard-header-title-area'>
                        <div className='ygc-treeCard-header-title'>
                            工程部位
                            </div>
                        <HeaderCheckbox
                            ref={el => this.headerCheckbox = el}
                            checkboxStateChange={this.checkboxStateChange}
                        />
                    </div>
                    <div className='ygc-treeCard-header-button-area'>
                        {
                            this.props.YGCreateButton({
                                btnTpl,
                                buttonClick: this.buttonClick
                            })
                        }
                    </div>
                </div>
                <div className='ygc-treeCard-table-area'>
                    {
                        this.props.YGCCreateTreeCard({
                            title: ['scode', 'sname'],
                            treeNodeKey: 'pkProjectpart',
                            childKey: 'childProjectpart',
                            selectTreeNodeAfter: this.selectTreeNodeAfter,
                            TreeBtnGroup: TreeBtnGroup,
                            treeNodeBtnClick: this.buttonClick,
                            treeSearchInput: this.getSearchUI(),
                            cardComponents: this.setCardComponents()
                        })
                    }
                </div>
            </div>

        )
    }

    initPageData = ({ successToastText } = {}) => {
        let selectV = this.projectRefer.gerReferValue('pkProject');
        if (!selectV) {
            this.props.vendorsDanger({ 'text': "请选择项目!" })
            this.props.treeCard.setTreeData({ data: [] })
            return
        }
        let value = this.headerCheckbox.getCheckState();
        console.log(value)
        value = value ? "0" : "1";
        this.props.ajax({
            url: URL.GET_LIST,
            data: { pkProject: selectV, queryStatus: value },
            success: (res) => {
                console.log(res)
                let toastM = successToastText ? successToastText : "查询成功!"
                this.props.vendorsSuccess({ 'text': toastM })
                this.props.treeCard.setEmptyTreeExpandedKeys([])
                this.props.treeCard.setTreeData({ data: res.data.result })
            }
        })
        this.form.setFormData({
            data: {
                scode: '',
                sname: '',
                enableStatus: '',
                pname: '',
                pcode: '',
            }
        })
        this.initPageState('browse');
    }

    checkboxStateChange = (value) => {
        this.initPageData()

    }

    selectTreeNodeAfter = ({ selectedData }) => {
        let { scode, sname, enableStatus, pname, pcode } = selectedData;
        if (pcode == 'topVirtual') {
            pname = '工程部位'
        }
        this.form.setFormData({
            data: {
                scode,
                sname,
                enableStatus,
                pname,
                pcode: ''
            }
        })
        // this.props.treeCard.setTreeNodeIsClick(true)
    }

    getSearchUI = () => {
        let ReferParams = {
            refType: 'grid',
            refPk: 'pkProject',
            showRefValue: "sname",
            label: "项目",
            isMultiSelectedEnabled: false,
            reqRef: {
                queryCondition: function () {
                    return {}
                    // let org = this.prop.search.getSearchValue({ refPk: 'pkProject', requireKey 'pkOrg'});
                },
                method: 'get',
                refUrl: "/projectInTeam/list",
                setCoByKey: [
                    { name: '项目编码', key: 'scode' },
                    { name: '项目名称', key: 'sname' },
                ],
            },
        }
        return <div className="search-area">
            <Refer style={{ width: "220px" }} referParams={ReferParams} ref={el => this.projectRefer = el} confirm={this.searchBtnClick}/>
        </div>
    }

    setCardComponents = () => {
        return (
            <Form ref={el => this.form = el} onFormAfter={this.onFormAfter} />
        )
    }
    enableStatusAfter = (key, value) => {
        let selectedKeys = this.props.treeCard.getTreeSelectedKeys(),
            selectedTreeData = this.props.treeCard.getTreeNodeDataByKey(selectedKeys),
            url = value == "1" ? "/projectpart/enable" : "/projectpart/disable",
            text = value == "1" ? "启用成功" : "停用成功";
        let { pkParent } = selectedTreeData;
        let { enableStatus } = this.props.treeCard.getTreeNodeDataByKey([pkParent])
        if (pkParent !== 'topVirtual' && enableStatus == "0") {
            this.form.resetFormData()
            this.props.vendorsDanger({ 'text': "所选数据的父节点为停用状态，请先启用父节点!" });
            return;
        }
        let checkboxV = this.headerCheckbox.getCheckState();
        checkboxV = checkboxV ? "0" : "1";
        this.props.ajax({
            url: url,
            data: { ...selectedTreeData, queryStatus: checkboxV },
            success: (res) => {
                this.props.treeCard.setTreeData({ data: res.data.result });
                this.props.vendorsSuccess({ 'text': text });
            },
            error: () => {
                this.form.resetFormData()
            }
        })
    }
    onFormAfter = (key, value) => {
        if (key == 'enableStatus') {
            if (value == "0") {
                let selectedKeys = this.props.treeCard.getTreeSelectedKeys(),
                    { childProjectpart } = this.props.treeCard.getTreeNodeDataByKey(selectedKeys);

                this.props.promptModal.isShow({
                    show: true,
                    title: '停用!',
                    content: childProjectpart ? '您确定要停用所选数据及所有子孙节点吗?' : '您确定要停用所选数据吗?',
                    confirm: () => {
                        this.enableStatusAfter(key, value)
                    },
                    cancel: () => {
                        this.form.resetFormData()
                    }
                })
                return;
            } else {
                this.enableStatusAfter(key, value)
            }
        }
    }

    searchBtnClick = () => {
        console.log(this.projectRefer.gerReferValue('pkProject'))
        this.initPageData()
    }

    initPageState(status, buttonKey) {
        if (status === 'browse') {
            this.props.treeCard.setTreeNodeIsClick(true)
        } else {
            this.props.treeCard.setTreeNodeIsClick(false)
        }
        this.props.button.setButtonState(status)
        this.form.setFormState(status, buttonKey)
    }

    buttonClick = ({ key, ...others }) => {
        this.buttonHandlers[key] && this.buttonHandlers[key]({ ...others })
    }

    saveClick = () => {
        this.saveFlag = 'add'
        this.commonSaveClick(URL.ADD_LIST)
    }
    editSaveClick = () => {
        this.saveFlag = 'edit'
        this.commonSaveClick(URL.EDIT_LIST)
    }

    commonSaveClick = (url) => {
        let { data } = this.form.getFormData();
        data.sname = this.props.vendorsTrimStr(data.sname)
        data.scode = this.props.vendorsTrimStr(data.scode)
        if (!data.scode) {
            this.props.vendorsDanger({ 'text': "部位编码不能为空!" });
            return;
        }
        if (!data.sname) {
            this.props.vendorsDanger({ 'text': "部位名称不能为空!" });
            return;
        }
        let value = this.headerCheckbox.getCheckState();
        value = value ? "0" : "1";
        let params = { ...data, queryStatus: value }
        if (this.saveFlag === 'edit') {
            this.props.ajax({
                url: URL.CHECK_REFERENCE,
                data: params,
                success: (res) => {
                    this.saveSureClick(url, params)
                },
                error: () => {
                    this.props.promptModal.isShow({
                        show: true,
                        title: '请注意!',
                        content: '如果修改所选数据，将会影响该数据做的所有单据引用数据，是否继续修改？',
                        confirm: () => {
                            this.saveSureClick(url, params)
                        },
                    })
                }
            })
        } else {
            this.saveSureClick(url, params)
        }
        
    }

    saveSureClick = (url, params) => {
        this.props.ajax({
            url: url,
            data: params,
            success: (res) => {
                this.props.vendorsSuccess({ 'text': '保存成功!' });
                this.props.treeCard.setTreeData({
                    data: res.data.result, callBack: () => {
                        if (this.saveFlag == 'add') {
                            let { operatePK } = res.data.result;
                            console.log(this.props.treeCard.getTreeNodeDataByKey([operatePK]))
                            let { pkParent } = this.props.treeCard.getTreeNodeDataByKey([operatePK])
                            if (operatePK) {
                                let expandedKeys = this.props.treeCard.getTreeExpandedKeys();
                                let selectedKeys = this.props.treeCard.getTreeSelectedKeys();
                                if (this.addType == 'child') {
                                    this.props.treeCard.setTreeExpandedKeys([...expandedKeys, pkParent])
                                    this.props.treeCard.setTreeSelectedKeys([operatePK])
                                } else {
                                    // 
                                }
                            }
                        }
                } });
                this.initPageState('browse');
            }
        })
    }
    cancelClick = () => {
        this.commonCancelClick()
    }

    editCancelClick = () => {
        this.commonCancelClick()
    }

    commonCancelClick = () => {
        this.props.promptModal.isShow({
            show: true,
            title: '取消',
            content: '确定要取消吗？',
            confirm: () => {
                this.initPageState('browse')
                this.form.resetFormData()
            },
            cancel: () => {

            }
        })
    }

    modalConfirmClick = () => {
        alert('sureClick')
    }

    modalCancelClick = () => {
        alert('cancelClick')
    }

    refreshClick = () => {
        this.initPageData({ successToastText: "刷新成功" })
        this.form.setFormData({
            data: {
                scode: '',
                sname: '',
                enableStatus: '',
                pname: '',
                pcode: ''
            }
        })
        this.initPageState('browse', 'refresh');
    }
    treeEditClick = ({ treeNodeData }) => {
        this.form.setFormData({
            data: {
                ...treeNodeData
            }
        })
        this.initPageState('edit')
    }

    treeAddBorClick = ({ treeNodeData }) => {
        let { pkParent } = treeNodeData,
            pkProjectV = this.projectRefer.gerReferValue('pkProject'),
            selectedTreeData = this.props.treeCard.getTreeNodeDataByKey([pkParent]);
        this.form.setFormData({
            data: {
                ...treeNodeData
            },
            callBack: () => {
                this.form.setFormData({
                    isCache: false,
                    data: {
                        scode: `${selectedTreeData.scode}`,
                        sname: '',
                        enableStatus: '1',
                        pkProject: pkProjectV,
                        pkParent,
                        pname: selectedTreeData.sname,
                        pcode: selectedTreeData.pcode,
                        parentInnerCode: selectedTreeData.innerCode
                    },
                    callBack: () => {
                        this.addType = 'bor'
                        this.initPageState('add')
                    }
                })
            }
        })

    }

    treeAddChildClick = ({ treeNodeData }) => {
        this.form.setFormData({
            data: {
                ...treeNodeData
            },
            callBack: () => {
                let { pkProjectpart, innerCode, sname, scode } = treeNodeData,
                    pkProjectV = this.projectRefer.gerReferValue('pkProject');
                let { enableStatus } = this.props.treeCard.getTreeNodeDataByKey([pkProjectpart])
                if (enableStatus == "0") {
                    this.props.vendorsDanger({ 'text': "当前部位停用，不允许增加下级!" });
                    return;
                }
                if (pkProjectpart == 'topVirtual') {
                    sname = '';
                    scode = ''
                }
                this.form.setFormData({
                    isCache: false,
                    data: {
                        scode: `${scode}`,
                        sname: '',
                        enableStatus: '1',
                        pname: sname,
                        pcode: scode,
                        pkProject: pkProjectV,
                        pkParent: pkProjectpart,
                        parentInnerCode: innerCode
                    },
                    callBack: () => {
                        this.addType = 'child'
                        this.initPageState('add')
                    }
                })
            }
        })
    }

    treeDelClick = ({ treeNodeData }) => {
        let value = this.headerCheckbox.getCheckState();
        value = value ? "0" : "1";
        this.props.ajax({
            url: URL.DEL_LIST,
            data: { ...treeNodeData, queryStatus: value },
            success: (res) => {
                this.props.vendorsSuccess({ 'text': "删除成功!" })
                this.props.treeCard.setTreeData({ data: res.data.result })
                this.initPageState('browse', 'refresh');
                this.form.setFormData({
                    data: {
                        scode: '',
                        sname: '',
                        enableStatus: '',
                        pname: '',
                        pcode: ''
                    }
                })
            }
        })
    }
}

export default createYGCPage({})(EngineeringLocation);
